const { regist, find, update, findtodevNum, del, findAlldev} = require("../model/devModel")
const moment = require('moment')//格式化时间的插件
const jwt = require("jsonwebtoken");
//日志操作
const { addLog } = require("../model/adminOpaLogs")

//添加设备
const register = async function (req, res) {
    //查看devName,devNum,devDate否传入
    if (!req.body.devName || !req.body.devDate || !req.body.devNum) {
        res.send({ state: false, status: 0, msg: "devName||devDate||devNum必填" })
        return;
    }
    //先查询数据库是否有相同的设备编号
    let isNameArr = await find({ devNum: req.body.devNum })//通过设备号来辨别是否注册
    if (isNameArr) {
        if (!isNameArr.length) {
            //设备未注册
            let cTime = moment().format("YYYY/MM/DD HH:mm:ss a")
            let date = { ...req.body, cTime }
            let result = await regist(date);
            if (result) {
                //添加日志
                let authorization = req.body.authorization || req.headers.authorization || req.query.authorization;
                let secrect = "How_are_you";
                jwt.verify(authorization, secrect, function (err, decode) {
                    //添加至日志数据库
                    let logQuery = {
                        admin: decode.name,
                        opa: "添加一个新设备设备:" + req.body.devNum,
                        cTime,
                    }
                    console.log(logQuery);
                    addLog(logQuery).then(r => {
                        res.send({ state: true, status: 1, logs: 1, msg: "设备添加成功,日志添加成功" })
                    })
                        .catch(err => {
                            res.send({ state: true, status: 1, logs: 0, msg: "设备添加成功,日志添加失败" })
                        })
                })
            } else {
                res.send({ state: false, status: 0, msg: "设备添加失败" })
            }
        } else {
            res.send({ state: false, status: 0, msg: "设备已注册" })//通过设备号来辨别
        }
    } else {
        res.send({ state: false, status: 0, msg: "查询失败" })
    }
}

//设备信息查询
//查询所有管理员信息
const finddever = async function (req, res, next) {
    let { devNum, devName, devAdmin, devUse } = req.body
    let query = {}
    if (devNum) { query.devNum = devNum }//如果存在devNum则加入query，反之不加入
    if (devName) { query.devName = devName }//如果存在devName则加入query，反之不加入
    if (devAdmin) { query.devAdmin = devAdmin }//如果存在devAdmin则加入query，反之不加入
    if (devUse) { query.devUse = devUse }//如果存在devUse则加入query，反之不加入
    let page = req.body['page'] || 1;
    let count = req.body['count'] || 5;
    let counts = {
        skip: (page - 1) * count,
        limit: count - 0
    }
    let findResult = await findtodevNum(query, counts);
    if (findResult) {//查找成功
        res.send({ state: true, status: 1, findResult })
    } else {
        res.send({ state: false, status: 0, msg: "查询失败" })
    }
}


//修改设备基本信息（devName,devNum,devDate不可更改） 通过devNum进行查找修改
const updateer = async function (req, res) {
    let { devNum } = req.body
    let query = { devNum }
    let updated = {}
    let { devSIM, devUse, devLocation, devAdmin } = req.body
    if (devSIM) { updated.devSIM = devSIM }
    if (devUse===true||devUse===false) { updated.devUse = devUse }
    if (devLocation) { updated.devLocation = devLocation }
    if (devAdmin) { updated.devAdmin = devAdmin }
    let result = await update(query, updated)
    if (result.nModified !== 0) {
        //添加日志
        let authorization = req.body.authorization || req.headers.authorization || req.query.authorization;
        let secrect = "How_are_you";
        jwt.verify(authorization, secrect, function (err, decode) {
            //添加至日志数据库
            console.log(JSON.stringify(updated));
            let cTime = moment().format("YYYY/MM/DD HH:mm:ss a")
            let logQuery = {
                admin: decode.name,
                opa: "修改了设备信息:" + JSON.stringify(updated),
                cTime,
            }
            console.log(logQuery);
            addLog(logQuery).then(r => {
                res.send({ state: true, status: 1, logs: 1, msg: "设备信息更新成功,日志添加成功" })
            })
            .catch(err => {
                res.send({ state: true, status: 1, logs: 0, msg: "设备信息更新成功,日志添加失败" })
            })
        })
    } else {
        res.send({ state: false, status: 0, msg: "设备信息一致,更新失败" })
    }
}

//删除设备 （通过传递devNum设备编号进行删除）
const dltdever = async function (req, res) {
    let { devNum } = req.body
    if (!devNum) {
        res.send({ state: false, status: 0, msg: "设备编号必传" })
    }
    let query = { devNum }
    let authorization = req.body.authorization || req.headers.authorization || req.query.authorization;
    let secrect = "How_are_you";
    jwt.verify(authorization, secrect, function (err, decode){
        if(decode.name==="root"){
            del(query).then(resdel=>{
                if(resdel.n){
                    //删除成功
                    //添加日志
                    //添加至日志数据库
                    let cTime = moment().format("YYYY/MM/DD HH:mm:ss a")
                    let logQuery = {
                        admin: decode.name,
                        opa: "删除设备:" + devNum,
                        cTime,
                    }
                    addLog(logQuery).then(r => {
                        res.send({ state: true, status: 1, logs: 1, msg: "设备删除成功,日志添加成功" })
                    }).catch(err => {
                        res.send({ state: true, status: 1, logs: 0, msg: "设备删除成功,日志添加失败" })
                    })
                }else{
                    res.send({ state: false, status: 0, msg: "删除出错" })
                }
            })
        }else{
            res.send({ state: false, status: 0, msg: "没有该权限(删除设备)" })
        }
    })
}

//获取所有设备记录
const findalldever = async function (req, res){
    let { devNum, devName, devAdmin, devUse } = req.body
    let query={}
    if (devNum) { query.devNum = devNum }//如果存在devNum则加入query，反之不加入
    if (devName) { query.devName = devName }//如果存在devName则加入query，反之不加入
    if (devAdmin) { query.devAdmin = devAdmin }//如果存在devAdmin则加入query，反之不加入
    if (devUse) { query.devUse = devUse }//如果存在devUse则加入query，反之不加入
    let result = await findAlldev(query)
    console.log(result.length);
    if(result){
        res.send({ state: true, status: 1, data:result })
    }else{
        res.send({ state: false, status: 0, msg: "查询失败" })
    }
}

module.exports = {
    register, updateer, finddever, dltdever,findalldever
}